<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客户管理 - 银行业务管理系统</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        
        .navbar-brand {
            font-weight: bold;
            color: #007bff !important;
        }
        
        .sidebar {
            min-height: calc(100vh - 56px);
            background-color: #343a40;
            padding-top: 20px;
        }
        
        .sidebar .nav-link {
            color: #adb5bd;
            padding: 10px 20px;
            border-radius: 0;
        }
        
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: #fff;
            background-color: #495057;
        }
        
        .main-content {
            padding: 20px;
        }
        
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
            margin-bottom: 20px;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid rgba(0, 0, 0, 0.125);
            font-weight: 600;
        }
        
        .table th {
            background-color: #f8f9fa;
            border-top: none;
            font-weight: 600;
        }
        
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        .search-form {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .modal-header {
            background-color: #007bff;
            color: white;
        }
        
        .required {
            color: red;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/admin">
                <i class="fas fa-university"></i>
                银行业务管理系统 - 管理员
            </a>
            
            <div class="navbar-nav ml-auto">
                <a class="nav-link" href="/">
                    <i class="fas fa-home"></i> 返回首页
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-none d-md-block sidebar">
                <div class="sidebar-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/admin">
                                <i class="fas fa-university"></i> 快捷操作
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/admin/customers">
                                <i class="fas fa-users"></i> 客户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/cards">
                                <i class="fas fa-credit-card"></i> 银行卡管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/deposit-types">
                                <i class="fas fa-piggy-bank"></i> 存款业务管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/trades">
                                <i class="fas fa-exchange-alt"></i> 交易管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-toggle="collapse" data-target="#viewsSubmenu" aria-expanded="true">
                                <i class="fas fa-eye"></i> 视图查询 <i class="fas fa-caret-down"></i>
                            </a>
                            <div class="collapse show" id="viewsSubmenu">
                                <ul class="nav flex-column ml-3">
                                    <li class="nav-item">
                                        <a class="nav-link" href="/admin/views/customer-cards">
                                            <i class="fas fa-credit-card"></i> 客户银行卡视图
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/admin/views/trade-details">
                                            <i class="fas fa-list-alt"></i> 交易明细视图
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-10 ml-sm-auto main-content">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-users"></i> 客户管理
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group mr-2">
                            <button type="button" class="btn btn-primary" onclick="showAddModal()">
                                <i class="fas fa-plus"></i> 新增客户
                            </button>
                            <button type="button" class="btn btn-success" onclick="exportCustomers()">
                                <i class="fas fa-download"></i> 导出数据
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="refreshTable()">
                                <i class="fas fa-sync-alt"></i> 刷新
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 搜索表单 -->
                <div class="search-form">
                    <form id="searchForm">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchCustomerName">客户姓名</label>
                                    <input type="text" class="form-control" id="searchCustomerName" placeholder="支持模糊查询">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchPid">身份证号</label>
                                    <input type="text" class="form-control" id="searchPid" placeholder="精确查询">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchTelephone">联系电话</label>
                                    <input type="text" class="form-control" id="searchTelephone" placeholder="支持模糊查询">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <div>
                                        <button type="button" class="btn btn-primary" onclick="searchCustomers()">
                                            <i class="fas fa-search"></i> 查询
                                        </button>
                                        <button type="button" class="btn btn-secondary ml-2" onclick="resetSearch()">
                                            <i class="fas fa-undo"></i> 重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchStartTime">创建开始时间</label>
                                    <input type="datetime-local" class="form-control" id="searchStartTime">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchEndTime">创建结束时间</label>
                                    <input type="datetime-local" class="form-control" id="searchEndTime">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 数据表格 -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-table"></i> 客户列表
                        <span class="badge badge-primary ml-2" id="totalCount">0</span>
                    </div>
                    <div class="card-body">
                        <div class="loading">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载数据...</p>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped table-hover" id="customerTable">
                                <thead>
                                    <tr>
                                        <th>
                                            <input type="checkbox" id="selectAll">
                                        </th>
                                        <th>客户编号</th>
                                        <th>客户姓名</th>
                                        <th>身份证号</th>
                                        <th>联系电话</th>
                                        <th>联系地址</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="customerTableBody">
                                    <!-- 数据将通过Ajax加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="分页导航">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页按钮将通过JavaScript生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 新增/编辑客户模态框 -->
    <div class="modal fade" id="customerModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="customerModalTitle">新增客户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="customerForm" novalidate>
                        <input type="hidden" id="customerId" name="customerId">
                        
                        <div class="form-group">
                            <label for="customerName">客户姓名 <span class="required">*</span></label>
                            <input type="text" class="form-control" id="customerName" name="customerName" 
                                   required maxlength="50" placeholder="请输入客户姓名">
                            <div class="invalid-feedback">请输入客户姓名（最多50个字符）</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="pid">身份证号 <span class="required">*</span></label>
                            <input type="text" class="form-control" id="pid" name="pid" 
                                   required pattern="^[0-9]{17}[0-9Xx]$" placeholder="请输入18位身份证号">
                            <div class="invalid-feedback">请输入正确的18位身份证号</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="telephone">联系电话 <span class="required">*</span></label>
                            <input type="text" class="form-control" id="telephone" name="telephone" 
                                   required pattern="^[0-9]{11}$" placeholder="请输入11位手机号">
                            <div class="invalid-feedback">请输入正确的11位手机号</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="address">联系地址</label>
                            <textarea class="form-control" id="address" name="address" 
                                      rows="3" maxlength="200" placeholder="请输入联系地址（可选）"></textarea>
                            <div class="invalid-feedback">联系地址最多200个字符</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveCustomer()">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        
        // 页面加载完成后初始化
        $(document).ready(function() {
            loadCustomers();
            
            // 全选/取消全选
            $('#selectAll').change(function() {
                $('input[name="customerIds"]').prop('checked', this.checked);
            });
        });
        
        // 加载客户数据
        function loadCustomers(page = 1) {
            currentPage = page;
            showLoading(true);
            
            const searchParams = getSearchParams();
            const params = {
                current: currentPage,
                size: pageSize,
                ...searchParams
            };
            
            $.get('/admin/customers/page', params)
                .done(function(result) {
                    if (result.code === 200) {
                        renderTable(result.data);
                        renderPagination(result.data);
                        $('#totalCount').text(result.data.total);
                    } else {
                        showError('加载数据失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败，请检查网络连接');
                })
                .always(function() {
                    showLoading(false);
                });
        }
        
        // 获取搜索参数
        function getSearchParams() {
            return {
                customerName: $('#searchCustomerName').val().trim(),
                pid: $('#searchPid').val().trim(),
                telephone: $('#searchTelephone').val().trim(),
                startTime: $('#searchStartTime').val(),
                endTime: $('#searchEndTime').val()
            };
        }
        
        // 渲染表格
        function renderTable(pageData) {
            const tbody = $('#customerTableBody');
            tbody.empty();
            
            if (pageData.records.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="8" class="text-center text-muted">
                            <i class="fas fa-inbox fa-2x mb-2"></i><br>
                            暂无数据
                        </td>
                    </tr>
                `);
                return;
            }
            
            pageData.records.forEach(customer => {
                const row = `
                    <tr>
                        <td>
                            <input type="checkbox" name="customerIds" value="${customer.customerId}">
                        </td>
                        <td>${customer.customerId}</td>
                        <td>${customer.customerName}</td>
                        <td>${customer.pid}</td>
                        <td>${customer.telephone}</td>
                        <td>${customer.address || '-'}</td>
                        <td>${formatDateTime(customer.createTime)}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="editCustomer(${customer.customerId})">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="btn btn-sm btn-outline-danger ml-1" onclick="deleteCustomer(${customer.customerId}, '${customer.customerName}')">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }
        
        // 渲染分页
        function renderPagination(pageData) {
            const pagination = $('#pagination');
            pagination.empty();
            
            totalPages = pageData.pages;
            
            if (totalPages <= 1) return;
            
            // 上一页
            const prevDisabled = currentPage === 1 ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${prevDisabled}">
                    <a class="page-link" href="#" onclick="loadCustomers(${currentPage - 1})">上一页</a>
                </li>
            `);
            
            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                const active = i === currentPage ? 'active' : '';
                pagination.append(`
                    <li class="page-item ${active}">
                        <a class="page-link" href="#" onclick="loadCustomers(${i})">${i}</a>
                    </li>
                `);
            }
            
            // 下一页
            const nextDisabled = currentPage === totalPages ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${nextDisabled}">
                    <a class="page-link" href="#" onclick="loadCustomers(${currentPage + 1})">下一页</a>
                </li>
            `);
        }
        
        // 显示/隐藏加载动画
        function showLoading(show) {
            if (show) {
                $('.loading').show();
                $('#customerTable').hide();
            } else {
                $('.loading').hide();
                $('#customerTable').show();
            }
        }
        
        // 搜索客户
        function searchCustomers() {
            loadCustomers(1);
        }
        
        // 重置搜索
        function resetSearch() {
            $('#searchForm')[0].reset();
            loadCustomers(1);
        }
        
        // 刷新表格
        function refreshTable() {
            loadCustomers(currentPage);
        }
        
        // 显示新增模态框
        function showAddModal() {
            $('#customerModalTitle').text('新增客户');
            $('#customerForm')[0].reset();
            $('#customerId').val('');
            $('#customerModal').modal('show');
        }
        
        // 编辑客户
        function editCustomer(customerId) {
            $.get(`/admin/customers/${customerId}`)
                .done(function(result) {
                    if (result.code === 200) {
                        const customer = result.data;
                        $('#customerModalTitle').text('编辑客户');
                        $('#customerId').val(customer.customerId);
                        $('#customerName').val(customer.customerName);
                        $('#pid').val(customer.pid);
                        $('#telephone').val(customer.telephone);
                        $('#address').val(customer.address);
                        $('#customerModal').modal('show');
                    } else {
                        showError('获取客户信息失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败');
                });
        }
        
        // 保存客户
        function saveCustomer() {
            const form = $('#customerForm')[0];
            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                return;
            }
            
            const customerId = $('#customerId').val();
            const customerData = {
                customerId: customerId || null,
                customerName: $('#customerName').val().trim(),
                pid: $('#pid').val().trim(),
                telephone: $('#telephone').val().trim(),
                address: $('#address').val().trim()
            };
            
            const url = customerId ? '/admin/customers' : '/admin/customers';
            const method = customerId ? 'PUT' : 'POST';
            
            $.ajax({
                url: url,
                method: method,
                contentType: 'application/json',
                data: JSON.stringify(customerData)
            })
            .done(function(result) {
                if (result.code === 200) {
                    showSuccess(customerId ? '客户信息修改成功' : '客户信息新增成功');
                    $('#customerModal').modal('hide');
                    loadCustomers(currentPage);
                } else {
                    showError('保存失败：' + result.message);
                }
            })
            .fail(function() {
                showError('网络请求失败');
            });
        }
        
        // 删除客户
        function deleteCustomer(customerId, customerName) {
            if (confirm(`确定要删除客户"${customerName}"吗？\n删除后将无法恢复！`)) {
                $.ajax({
                    url: `/admin/customers/${customerId}`,
                    method: 'DELETE'
                })
                .done(function(result) {
                    if (result.code === 200) {
                        showSuccess('客户删除成功');
                        loadCustomers(currentPage);
                    } else {
                        showError('删除失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败');
                });
            }
        }
        
        // 导出客户数据
        function exportCustomers() {
            window.open('/admin/customers/export', '_blank');
        }
        
        // 工具函数
        function formatDateTime(dateTime) {
            if (!dateTime) return '-';
            const date = new Date(dateTime);
            return date.getFullYear() + '-' + 
                   String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                   String(date.getDate()).padStart(2, '0') + ' ' +
                   String(date.getHours()).padStart(2, '0') + ':' + 
                   String(date.getMinutes()).padStart(2, '0') + ':' + 
                   String(date.getSeconds()).padStart(2, '0');
        }
        
        function showSuccess(message) {
            showAlert('success', message);
        }
        
        function showError(message) {
            showAlert('danger', message);
        }
        
        function showAlert(type, message) {
            const alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
                    ${message}
                    <button type="button" class="close" data-dismiss="alert">
                        <span>&times;</span>
                    </button>
                </div>
            `;
            
            $('.main-content').prepend(alertHtml);
            
            setTimeout(function() {
                $('.alert').alert('close');
            }, 3000);
        }
    </script>
</body>
</html>
